<?php


namespace App\Services;

use App\Models\Car;
use App\Models\Company;
use App\Models\DriverCar;
use App\Models\DriverOthers;
use App\Models\Drivers;
use App\Models\Licence;
use App\Models\Region;
use App\Models\ServiceType;
use App\Models\UploadFile;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Reprover\Amap\Exception;

class DriversService extends BaseService
{
    /**
     * 提交资料
     */
    public function post_add($user, $data)
    {

        DB::beginTransaction();
        try {
            $drivers_id = $this->drivers_add($user, $data);
            /**
             * 所属权：1-个人，2-公司  3别人的车
             */
            if ($data['ownership'] <> '3' || $data['ownership'] <> 3) {
                $id = $this->car_after($data, $user, $drivers_id);
                $this->driver_car($drivers_id, $id);
            }
            $where = ['status' => '1'];
            if ($data['types'] == 1) {
                $where = ['taxi_status' => '1'];
            }
            Drivers::query()->where('id', $drivers_id)->update($where);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();//事务回滚
            return_bobc($e->getMessage());
        }
        return true;
    }

    /**
     * 司机资料提交 1 2, 驾驶证提交
     */
    protected function drivers_add($user, $data)
    {
        $flight = new  Drivers();
        $res = $flight->where(['user_id' => $user->id])->first();
        $flight->user_id = $user->id;
        $flight->phone = $user->phone;
        $flight->real_name = $data['real_name'] ? $data['real_name'] : '';
        $flight->identity = $data['identity'] ? $data['identity'] : '';
        $flight->identity_photo = $data['identity_photo'] ? $data['identity_photo'] : '';
        $flight->licence_id = $data['licence_id'] ? $data['licence_id'] : '';
        $flight->licence_photo = $data['licence_photo'] ? $data['licence_photo'] : '';
        $flight->license_start = date('Y-m-d');
        $flight->licence_end = $data['licence_end'] ? $data['licence_end'] : '';
        $flight->company_id = $data['company_id'] ? $data['company_id'] : '';
        $flight->city = $data['city'] ? $data['city'] : '';
        $flight->work_scope = $data['work_scope'] ? $data['work_scope'] : '';
        $flight->identity_end = date('Y-m-d H:i:s', strtotime($data['identity_end']));
//        $flight->identity_end =$data['identity_end']?date('Y-m-d H:i:s',strtotime($data['identity_end'])):date('Y-m-d H:i:s');
        if ($res) $res ? $flight->where('id', $res->id)->update($flight->toArray()) : $flight->save();
        return $flight->id ? $flight->id : $res->id;
    }

    protected function drivers_edit_add(User $user, $data)
    {
        $flight = new  Drivers();

        $res = $flight->where(['user_id' => $user->id])->first();
        $flight->user_id = $user->id;
        $flight->phone = $user->phone;
        $flight->real_name = $data['real_name'] ? $data['real_name'] : '';
        $flight->identity = $data['identity'] ? $data['identity'] : '';
        $flight->identity_photo = $data['identity_photo'] ? $data['identity_photo'] : '';
        $flight->licence_id = $data['licence_id'] ? $data['licence_id'] : '';
        $flight->licence_photo = $data['licence_photo'] ? $data['licence_photo'] : '';
        $flight->license_start = date('Y-m-d');
        $flight->licence_end = $data['licence_end'] ? $data['licence_end'] : '';
        $flight->company_id = $data['company_id'] ? $data['company_id'] : '';
        if ($data['types'] == 0) {
            $flight->status = $res ? '1' : '-1';
        } else {
            $flight->taxi_status = $res ? '1' : '-1';
        }
        $flight->city = $data['city'] ? $data['city'] : '';
        $flight->work_scope = $data['work_scope'] ? $data['work_scope'] : '';
        $flight->identity_end = date('Y-m-d H:i:s', strtotime($data['identity_end']));
        if (!$res) {
            $flight->save();
        } else {
            $flight->where('id', $res->id)->update($flight->toArray());
        }
        return true;
    }

    /**
     * 车辆信息提交
     */
    public function car_after($data, $user, int $drivers_id)
    {
        if ($data['types'] == '0') {
            $info = DriverCar::query()->where('driver_id', $drivers_id)->with(['car', 'drivers'])->first();
            $car = new Car();
            $car->number = $data['car_num'];
            $car->brand_id = $data['brand_id'];
            $car->restriction = $data['restriction'];
            $car->people = $data['people'];
            $car->colour = $data['colour'];
            $car->company_id = $data['company_id'];
            $car->license_driving = $data['license_driving'];
            $car->ownership = $data['ownership'];
            $car->type = $data['type']; //业务类型
            if ($info) {
                if ($info->drivers->user_id == $user->id) {
                    $car->where('id', $info->car_id)->update($car->toArray());
                }
            } else {
                $car->save();
            }
            return $car->id ? $car->id : $info->car_id;
        } else {
            $car = new Car();
            $car->number = $data['car_num'];
            $car->brand_id = $data['brand_id'];
            $car->restriction = $data['restriction'];
            $car->people = $data['people'];
            $car->colour = $data['colour'];
            $car->company_id = $data['company_id'];
            $car->license_driving = $data['license_driving'];
            $car->ownership = $data['ownership'];
            $car->type = $data['type']; //业务类型
            $car->save();
            return $car->id;
        }

    }

    /**
     * 司机车辆关联表
     */
    public function driver_car($drivers_id, $id)
    {
        if (!DriverCar::query()->where(['car_id' => $id, 'driver_id' => $drivers_id])->first()) {
            return DriverCar::query()->insert(['car_id' => $id, 'driver_id' => $drivers_id]);
        }
    }

    /**
     * 绑定司机
     */
    public function bind_driver_car(array $data)
    {
        $model = DriverCar::query();
        if ($model->where(['car_id' => $data['car_id'], 'driver_id' => $data['driver_id']])->first()) {
            return_bob('该司机与车已经绑定');
        }
        $data = [
            'car_id' => $data['car_id'] ? $data['car_id'] : '',
            'driver_id' => $data['driver_id'] ? $data['driver_id'] : '',
            'host' => $data['host'] ? $data['host'] : '0',
        ];
        return $model->insert($data);
    }


    /**
     * 审核进度
     */
    public static function status(User $user)
    {

        $driver_id = $user->driver()->first() ? $user->driver()->first()->id : 0;
        $res_check = Drivers::query()
            ->with(['company:id,city_id', 'driver_others:id,driver_id,company_id,status'])
            ->where('id', $driver_id)
            ->select(['status', 'source', 'reject_remark', 'city', 'company_id', 'id', 'type as form', 'taxi_status'])
            ->first();
        if (!empty($res_check->company->city_id)) {
            if ($res_check) {
                $city = \App\Models\ServiceCity::query()->where('city_id', $res_check->company->city_id)->first('city_name');
                if ($city) {
                    if (!$res_check->driver_others) $res_check['driving_status'] = -2;
                    $res_check['driving_status'] = $res_check->driver_others ? $res_check->driver_others->status : -2;
                    $res_check['city'] = $city->city_name;
                    $res_check['form'] = self::res_check_status($res_check->status, $res_check['driving_status'], $res_check->taxi_status); //more为空
                    unset($res_check->company, $res_check->driver_others);
                    return $res_check;
                }
            }
        }
        return ['status' => -2, 'taxi_status' => -2, 'driving_status' => -2, 'source' => 1, 'reject_remark' => '', 'city' => '', 'form' => ''];
    }

    /**
     * @param $status  快车状态
     * @param $driving_status 代驾状态
     * @param $taxi_status 出租车状态
     * @return string
     */
    private static function res_check_status($status, $driving_status, $taxi_status)
    {
        if ($status == '2' && $driving_status == '2' && $taxi_status == '2') {
            return '1,2';
        } elseif ($status == '2' && $driving_status != '2' && $taxi_status != 2) {
            return '1';
        } elseif ($taxi_status == '2' && $driving_status != '2' && $status != '2') {
            return '1';
        } else if ($status == 2 && $driving_status == '2' && $taxi_status != 2) {
            return '1,2';
        } else if ($taxi_status == '2' && $driving_status == '2' && $status != '2') {
            return '1,2';
        } else if ($status == '2' && $taxi_status == '2' && $driving_status != '2') {
            return '1';
        } else if ($driving_status == '2' && $status != '2' && $taxi_status != '2') {
            return '2';
        } else {
            return '';
        }
    }

    /**
     * 司机资料提交中途退出保存
     */
    public function drivers_ubmission_after(array $data)
    {
        return $this->drivers_edit_add(Auth::user(), $data);
    }

    /**
     * 司机资料查看
     */
    public function drivers_info()
    {
        $drivers_id = UsersService::driver_id(Auth::user());
        return DriverCar::with(['car', 'drivers'])->where('driver_id', $drivers_id)->first()->toArray();
    }

    /**
     * 业务类型
     */
    public function service(int $type)
    {
        if ($type === 0) {
            $type = '优米';
        } else {
            $type = '出租车';
        }
        return ServiceType::query()->where('status', 1)->where('name', 'like', '%' . $type . '%')->select(['id', 'service_id', 'img', 'name'])->get();
    }

    /**
     * 准驾车型
     */
    public function licence_list()
    {
        return Licence::query()->get()->toArray();
    }

    /**
     * @param array $licence_photo
     * 查询图片
     */
    public function UploadFile($licence_photo)
    {
        $identity_photos = [];
        if (!empty($licence_photo)) {
            if (!is_array($licence_photo)) $licence_photo = json_decode($licence_photo, true);
            $res = UploadFile::query()->whereIn('id', $licence_photo)->select(['id', 'file_url', 'file_name'])->get(); //身份证图片

            if ($res) {
                foreach ($res as $key => $val) {

                    $identity_photos[] = $val['file_path'];
                }
                return $identity_photos;
            }
        }

    }

    /**
     * @param int $drivers_id
     * 司机申请资料查看
     */
    public function drivers(int $types)
    {
        $driver_id = UsersService::driver_id(Auth::user());
        if (!$driver_id) return_bobc('您还不是司机,请填写资料完成认证信息');
        $driver = Drivers::query()->where('id', $driver_id)->with(['head:id,file_url,file_name'])->first()->toArray();
        if (!is_array($driver['identity_photo'])) $driver['identity_photo'] = json_decode($driver['identity_photo'], true);
        if (!is_array($driver['licence_photo'])) $driver['licence_photo'] = json_decode($driver['licence_photo'], true);
        $driver['identity_photos'] = $this->UploadFile($driver['identity_photo']); //身份证图片合集
        $driver['licence_photos'] = $this->UploadFile($driver['licence_photo']);  //驾照照片
        if ($types === 0) {
            $type = '1,2';
        } else {
            $type = '3';
        }
        if (!$car = DriverCar::query()->with(['car' => function ($query) {
            $query->select('id', 'number', 'plate_colour', 'restriction', 'ownership', 'company_id', 'type', 'people', 'brand_id', 'colour', 'license_driving', 'outward_status');
        }])
            ->when($type, function ($query) use ($type) {
                return $query->whereHas('car', function ($query) use ($type) {
                    return $query->whereIn('type', explode(',', $type));
                });
            })
            ->where('driver_id', $driver_id)
            ->first()) {
            return $driver;
        } else {
            $car = $car->toArray();
            if (!is_array($car['car']['license_driving'])) $car['car']['license_driving'] = json_decode($car['car']['license_driving'], true);
            $car['car']['license_drivings'] = $this->UploadFile($car['car']['license_driving']);  //行驶证加上车辆照片
            return array_merge($driver, $car);
        }
    }

    /**
     * @param $linkphone
     * @param $linkman
     * @param User $user
     * @return bool
     * @throws \App\Exceptions\BobException
     * 添加紧急联系人
     */
    public function linkman_add($linkphone, $linkman, User $user)
    {
        $map = [
            'linkman' => $linkman,
            'linkphone' => $linkphone,
        ];
        // TODO 留这儿
        if (!Drivers::query()->where('id', $user->driver()->first()->id)->update($map)) {
            return_bobc('error');
        };
        return true;
    }

    /**
     * 代驾资料提交认证
     */
    public function valet_driver_add(array $data, $user)
    {
        try {
            DB::transaction(function () use ($data, $user) {
                $driver_id = $this->drivers_adds($data, $user);
                $this->driver_others($driver_id, $data['company_id'], $data['city'], $data['identity_photo'], $data['licence_photo'], $data['licence_id']);
            });
        } catch (\Exception $e) {

            return_bobc($e->getMessage());
        }
        return true;
    }

    protected function drivers_adds(array $data, $user)
    {
        $flight = new  Drivers();
        $res = $flight->where(['user_id' => $user->id])->first();
        $flight->user_id = $user->id;
        $flight->phone = $user->phone;
        $flight->address = $data['address'];
        $flight->linkman = $data['linkman'];
        $flight->linkphone = $data['linkphone'];
        $flight->relationship = $data['relationship'];
        $flight->number = $data['number'];
        $flight->native_place = $data['native_place'];
        $flight->real_name = $data['real_name'] ? $data['real_name'] : '';
        $flight->identity = $data['identity'] ? $data['identity'] : '';
        $flight->identity_photo = $res ? $res->identity_photo : $data['identity_photo'];
        $flight->licence_id = $res ? $res->licence_id : $data['licence_id'];
        $flight->licence_photo = $res ? $res->licence_photo : $data['licence_photo'];
        $flight->license_start = date('Y-m-d');
        $flight->company_id = $res ? $res->company_id : $data['company_id'];
        $flight->city = $res ? $res->city : $data['city'];
        $flight->type = $res ? $res->type . ',2' : '2';
        $flight->license_first = $data['license_first'] ? $data['license_first'] : '';
        if ($res) $res ? $flight->where('id', $res->id)->update($flight->toArray()) : $flight->save();
        return $flight->id ? $flight->id : $res->id;
    }

    /**
     * @param int $driver_id
     * @param int $company_id
     * @return bool
     * 代驾附加信息
     */
    protected function driver_others(int $driver_id, int $company_id, int $city, $identity_photo, $licence_photo, $licence_id)
    {
        $other = DriverOthers::query()->where('driver_id', $driver_id)->first();
        if (!$other) {
            $others = new DriverOthers;
            $others->driver_id = $driver_id;
            $others->company_id = $company_id;
            $others->city = $city;
            $others->identity_photo = $identity_photo;
            $others->licence_photo = $licence_photo;
            $others->licence_id = $licence_id;
            $others->status = '1';
            $others->auditor_id = 1;
            if ($others->save()) return true;
        } else {
            $other->driver_id = $driver_id;
            $other->company_id = $company_id;
            $other->city = $city;
            $other->identity_photo = $identity_photo;
            $other->licence_photo = $licence_photo;
            $other->licence_id = $licence_id;
            $other->status = '1';
            $other->auditor_id = 1;
            if ($other->save()) return true;
        }
        return true;
    }

    /**
     * 地址
     */
    public function region(int $pid)
    {
        if (Cache::has('city')) {
            $data = Cache::get('city');
        } else {
            $data = Region::query()->select(['id', 'pid', 'name'])->get()->toArray();
            Cache::put('city', $data, 60 * 60 * 24);
        }
        $list = $this->getSon($data, 0);
        return $list;
    }

    /**
     * @param $data
     * @param $pid
     * @return array
     * 递归
     */
    public static function findSon($data, $pid)
    {
        $childs = [];
        foreach ($data as $v)
            if ($v['pid'] == $pid) {
                $childs[] = $v;
            }
        return $childs;
    }

    /**
     * @param $data
     * @param $pid
     * @return array
     */
    public static function getSon($data, $pid)
    {
        $childs = self::findSon($data, $pid);
        foreach ($childs as $k => $v) {
            $res = self::getSon($data, $v['id']);
            if ($res != '') {
                $childs[$k]['children'] = $res;
            }
        }
        return $childs;
    }

    /**
     * @param User $user
     * @return array
     * @throws \App\Exceptions\BobException
     * 代驾资料回显
     */
    public function valet_driver_data(User $user)
    {
        $drivers_id = $user->driver()->first()->id;  //司机ID
        if (!$drivers_id) return_bobc('代驾司机不存在');
        $res = Drivers::query()
            ->select(['id', 'user_id', 'phone', 'real_name', 'linkman', 'linkphone', 'address', 'identity', 'license_first', 'source', 'type', 'number', 'native_place', 'relationship'])
            ->with('driver_others:id,company_id,identity_photo,licence_photo,licence_id,city,driver_id,status')
            ->where('id', $drivers_id)
            ->first();
        if ($res->driver_others) {
            $res->toArray();
            if (!is_array($res['driver_others']['identity_photo'])) $res['identity_photo'] = json_decode($res['driver_others']['identity_photo'], true);
            if (!is_array($res['driver_others']['licence_photo'])) $res['licence_photo'] = json_decode($res['driver_others']['licence_photo'], true);
            $res['identity_photos'] = $this->UploadFile($res['identity_photo']); //身份证图片合集
            $res['licence_photos'] = $this->UploadFile($res['licence_photo']);  //驾照照片
            $name = Company::query()->where('id', $res['driver_others']['company_id'])->first('name');  //驾照照片
            $res['company_name'] = $name ? $name->name : '';
            $city = Region::query()->where('id', $res['driver_others']['city'])->first('name');  //驾照照片
            $res['city_name'] = $city ? $city->name : '';
        }
        return $res;
    }

    /**
     * 公司列表
     */
    public function company_list(int $city_id)
    {
        return Company::query()->select(['id', 'name', 'address'])->where('city_id', $city_id)->where('status', 1)->get();
    }
}

